<!doctype html>
<html lang="en">
	<head>
	    <meta charset="utf-8">
	    <title>药品名称</title>
	    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
	    <meta name="apple-mobile-web-app-capable" content="yes">
	    <meta name="apple-mobile-web-app-status-bar-style" content="black">
	    <link href="css/mui.min.css" rel="stylesheet"/>
	    <link rel="stylesheet" href="css/grandeHealth.css"/>
	    <style>
			.mui-media-bodys {background: #fff;width:100%;border-bottom:1px solid #DDDDE0;padding: 11px 15px;color: #999;}
			.mui-indexed-list{overflow: hidden;}
			.mui-search {width: 78%;float: left;}
			input[type=search]{background: #fff;border: 1px solid #ccc;height: 45px;border: 0;margin-bottom: 5px;}
			.mui-search .mui-placeholder {line-height: 45px;}
			.Yescfim,.saveFim{height: 45px;float: right;border-radius: 5px;width: 20%;background: #39ABE7;color: #fff;border: 0;}
			.mui-icon-clear{line-height: 30px;}
			.mui-media-body{overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}
			.mui-search:before {margin-top: -13px;}
			#pullrefresh{margin-top: 50px;}
	    	.hisAll_left{margin: 5px;float: left;}
	    	#his-dele{padding: 2px 7px;float: right;}
			.history{overflow: hidden;width: 100%;}
    		.history li {border-radius: 15px;float: left;line-height:25px;background: rgba(0,0,0,0.05);padding:5px 15px;color: #666;margin: 5px;}
			.mui-content{margin-top:-60px}
	</style>
	</head>
	<body>
		<!--<header>class="mui-bar mui-bar-nav" style="display: block;height: 64px;padding-top:20px">
	      <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left" id="goBack"></a>
	    </header>-->
	    
		<div class="mui-content">
			<div class="mui-indexed-list">
				<div class="mui-indexed-list-search mui-input-row mui-search">
					<input type="search" id="searchInput" value="" class="inputValue mui-input-clear mui-indexed-list-search-input" placeholder="搜索药品">
				</div>
				<button class="Yescfim saveFim" id="search">搜索</button>
				 <div id="result"></div>
			</div>
			<p id="info" style="display: none;"></p>
			<p id="infos" style="display: none;"></p>
			<p id="numnit" style="display: none;"></p>
			<p id="smlunt" style="display: none;"></p>
			
			<div id="hisAll" style="display: none;">
				<div class="hisAll_left">历史搜索</div>
				<!--删除按钮-->
				<!--<div id="his-dele">X</div>-->
				<span class="mui-icon mui-icon-trash" id="his-dele"></span>
				<!--数据存储-->
				<ul class="history"></ul>
			</div>	
		</div>

		<!--下拉刷新容器-->
		<div id="infoAlls">
			<div class="mui-media-bodys" id="tishi" style="display: none;">搜索发现</div>
		</div>
	    <div class="mui-scroll-wrapper" id="pullrefresh">
    		
      		<div class="mui-scroll">
		        <!-- 数据列表 -->
		        <ul class="mui-table-view mui-table-view-radio mui-row" id="getalldoclist">
		
		 		</ul>
      		</div>
	    </div>
		<script src="js/jquery-1.7.2.min.js"></script>
		<script src="js/mui.min.js"></script>
 		<script src="js/grandeHealth.js"></script>
		<script src="js/medicalRecord.js"></script>
		<script>
			/*
			 * 默认显示历史记录
			 */
			$('#hisAll').show(),$('#pullrefresh').hide(),$('#infoAlls').hide();
					
			/*
			 * 监听历史记录同步到input
			 */
			$( ".history" ).on( "click", ".word-break", function() {
				var div = $(this).text();
				$('.inputValue').val(div),$('#searchInput').focus();
			});
			
			/*
			 * 监听input如果为空显示历史记录
			 */
			$('#searchInput').bind('input propertychange', function() {
			    if($(this).val() == 0){
					$('#hisAll').show(),$('#infoAlls').hide(),$('#pullrefresh').hide();					
			    }else{
			    	$('#hisAll').hide(),$('#infoAlls').show(),$('#pullrefresh').show();
			    }
			});
			
			/*
			 * 监听if执行input重置标则显示历史记录
			 */
			mui("body").on("tap", ".mui-icon-clear", function() {
				if($(this).val() == 0){
					$('#hisAll').show(),$('#infoAlls').hide(),$('#pullrefresh').hide();					
			    }else{
			    	$('#hisAll').hide(),$('#infoAlls').show(),$('#pullrefresh').show();
			    }
			})
			
	 	 	var hisTime;//获取搜索时间数组	  
		  	var hisItem;//获取搜索内容数组	  
		  	var firstKey;//获取最早的1个搜索时间
		  
		  	function init (){
		
				hisTime = [];//时间数组置空
		    	hisItem = [];//内容数组置空	
			    for(var i = 0; i < localStorage.length; i++){//数据去重
			      if(!isNaN(localStorage.key(i))){//判断数据是否合法
			        hisTime.push(localStorage.key(i));
			      }
			    }
		
			    if(hisTime.length > 0) {	
		      	hisTime.sort();//排序
						for (var y = 0; y < hisTime.length; y++) {
			        localStorage.getItem(hisTime[y]).trim() && hisItem.push(localStorage.getItem(hisTime[y]));
			     	}	
			    }
			    
			    $(".history").html("");//执行init(),每次清空之前添加的节点
	
			    for(var i = 0; i < hisItem.length; i++){
	
			      $(".history").prepend('<li class="word-break">'+hisItem[i]+'</li>');	
			    }		 	    
		  	}
		  	  
			init();//调用
		
			//清除记录功能	  
			mui("body").on("tap", "#his-dele", function() {
			  	var f = 0;
			    for(;f<hisTime.length;f++){
			      localStorage.removeItem(hisTime[f]);
			    }
			    init();
			    $('#hisAll').hide();
			})
	  
			
		</script>
		
		<script>

			var arry = {};
			var count = 2;
			var totalNumber;//总条数
			
			/*
			 * 搜索药品按钮
			 */
			$('.Yescfim').removeClass('saveFim');

			var medication = [];
			mui("body").on("tap", ".Yescfim", function() {
				
				selectEarchDoc();
				$('#searchInput').blur();//执行搜索后让其失去焦点
				
				var value = $(".inputValue").val();
			    var time = (new Date()).getTime();
			
			    if(!value){
			      mui.toast("搜索不能为空");
			      return false;
			    }
 
			    //输入的内容localStorage有记录
			    if($.inArray(value,hisItem)>=0){
			      for(var j = 0;j<localStorage.length;j++){
			        if(value==localStorage.getItem(localStorage.key(j))){
			          localStorage.removeItem(localStorage.key(j));
			        }
			      }
			      localStorage.setItem(time,value);  
			    } else{
			      //由于限制了只能有6条记录，所以这里进行判断
			      if(hisItem.length>4){
			        firstKey = hisTime[0]
			        localStorage.removeItem(firstKey);
			        localStorage.setItem(time,value);
			      }else{
			        localStorage.setItem(time,value)
			      }
			    }
		
			    init();	
			})
			  	
			/*
			 * keydown调用
			 */
			$('input[type=search]').keydown(function(event){
				selectEarchDoc();//调用搜索方法			
			})
			/*
			 * ajax输入框内容改变
			 */		
			function selectEarchDoc(){
				
				var drugName = $('input[type="search"]').val();//输入框值								
				//验证特殊字符
				if(drugName.indexOf("'")>-1 || drugName.indexOf("\"")>-1 || drugName.indexOf("=")>-1 || drugName.indexOf("-")>-1 || drugName.indexOf("+")>-1 || drugName.indexOf("*")>-1 || drugName.indexOf("%")>-1 || drugName.indexOf("&")>-1){
					document.getElementById('tishi').innerHTML="请勿包含特殊字符！！";//放值的框
					return;
				}
				
				if(drugName.trim() != ''){

					drugName = drugName.trim();				
					var webUrl = XHDOC_WEBBASE + "dtcasehistory/getdrugs?&pageSize=10&name="+drugName;
					try {
						$.ajax({
						    url: webUrl,
						    type: "POST",
							async: false,
							timeout:8000,
							success: function(data) {
							  	try {
							  		data = data.trim();
					  				data = JSON.parse(data)
								    if(data.code == 000){
								    	arry = data.data;
								    	$('.mui-table-view').html('');						    	
								    	for(var i = 0 ; i < arry.parameterType.length; i ++){				    		
								    		var duglhtml = 
							    					'<li class="mui-table-view-cell" name="'+arry.parameterType[i].maxun+'" id="'+arry.parameterType[i].minun+'">'+
														'<a href="javascript:;" class="mui-navigate-right">'+
											                '<div class="mui-media-body">'+arry.parameterType[i].name+'('+arry.parameterType[i].spec+')'+'</div>'+
														'</a>'+
													'</li>';									
											$('.mui-table-view').append(duglhtml);
											$('#tishi').html('搜索发现').show();
//											console.log(arry.parameterType[i].maxun)
//											console.log(arry.parameterType[i].minun)
								    	}							    		
								    	
								    	$('#hisAll').hide();
										$('#pullrefresh').show(); 
										$('#infoAlls').show();
			
								    	if(arry.parameterType == ""){
		
								    		$('#tishi').html('没有找到该药品，请试试重新输入!').show(); 	 
								    	}					    		
								    }else if(data.code == 001){
								    	mui.toast('请求出错'); 
								    }
		  
							  	} catch(e) {						    
								    mui.toast('获取数据失败'); 
							  	}
							},
							error: function(xhr, textStatus, error) {						
						  		if(textStatus == "error")
								mui.toast('请检查网络连接');
						  	}		
					  	});				  					
					
					} catch(e) {
					  mui.toast("请检查网络连接");
				   	}
				}								
			}
									
			/*
			 * 当搜索框获取焦点时变换按钮
			 */
			$('#searchInput').focus(function(){
				$('.saveFim').addClass('Yescfim').removeClass('saveFim').html('搜索');
				$('.mui-table-view-cell').removeClass('mui-selected');
			})
			
			/*
			 * 勾选药品
			 */
			var info = document.getElementById("info").innerHTML;
			var infos = document.getElementById("infos").innerHTML;
			var numnit = '';
			var smlunt = '';
//			maxun minun
//			
//			 smlunt
			document.querySelector('.mui-table-view.mui-table-view-radio').addEventListener('selected',function(e){			
				var details = e.detail.el.innerText;//选取值							
				info = details.replace(/\(.*?\)/g,'');//括号外内容	
				info = info.replace(/[\r\n]/g, "");//去回车空格				
				var re = /\([^\)]+\)/g;
				details = details.match(re)[0];
				details = details.substring(1,details.length-1);				
				infos = details;//括号里内容
				infos = infos.replace(/[\r\n]/g, "");//去回车空格
				numnit = e.detail.el.getAttribute('id');//数量单位
				smlunt = e.detail.el.getAttribute('name');//小剂量单位
				$('.Yescfim').addClass('saveFim').removeClass('Yescfim').html('确定');
				$('#searchInput').blur();
				 
			});

			/*
			 * 确定存储选择的药品及规格
			 */
			mui("body").on("tap", ".saveFim", function() {
				yongyaofanan.update('drunam',info);	
				yongyaofanan.update('unit',infos);
				yongyaofanan.update('numnit',numnit);	
				yongyaofanan.update('smlunt',smlunt);
				mui.back();
			})
									
			/*
			 * 返回用药方案页并传值    此处需修改，不能跳转，返回时传值
			 */
			mui("body").on("tap", "#goBack", function() {
				window.android.showpage('medicationPlan.html');
			})
			
			/*
			 * 返回用药方案页并传值
			 */
			try {
				
				if(XHDOC_BROWSETYPE == 'IOS') {
				
					//调用IOS的返回事件
					
				} else if(XHDOC_BROWSETYPE == 'ANDROID') {

					//调用ANDROID的返回事件

				}else{
					mui.back();
				}
	
			} catch(e) {
				console.log(e);
			}
													
			/*
			 * 初始化上下拉加载
			 */
			mui.init({
		        pullRefresh: {
		          container: '#pullrefresh',
		          down: {
		            callback: pulldownRefresh,
		            auto: true
		          },
		          up: {
		            contentrefresh: '正在加载...',
		            callback: pullupRefresh,
		            auto: true
		          }
		        }
	      	});


			/*
			 * 请求数据
		 	*/
			function jiaohu() {
				var drugName = $('input[type="search"]').val();//药品名称
				if(drugName == ''){
					return;
				}
				var webUrl = XHDOC_WEBBASE + "dtcasehistory/getdrugs?&pageSize=10&name="+drugName;
				try {
				  	$.ajax({
					    url: webUrl,
					    type: "POST",
						async: false,
						dataType: "json",
						data: {
						  pageNo: count
						},
						success: function(data) {					
							totalNumber = Math.ceil(data.data.pageSize/10);//总条数
							console.log(data)
						  	try {
						  	
							    if(data.code == 000){
							    	arry = data.data;							    		
							    	
							    }else if(data.code == 001){
							    	mui.toast('请求出错'); 
							    }
	  
						  	} catch(e) {						    
							    mui.toast('获取数据失败'); 
						  	}
						},
						error: function(xhr, textStatus, error) {						
					  		if(textStatus == "error")
							mui.toast('请检查网络连接');
					  	}
				  	});

				} catch(e) {
				  mui.toast("请检查网络连接");
				
			   	}
			};
	
	
			/**
			   * 下拉刷新具体业务实现
			*/
		  	function pulldownRefresh() {
		  	
		    	jiaohu();
			    setTimeout(function() {	          
			      var table = document.body.querySelector('.mui-table-view');
			      var cells = document.body.querySelectorAll('.mui-table-view-cell');
			      for(var i = 0; i < arry.length; i++) {
			        var li = document.createElement('li');
			        li.className = 'mui-table-view-cell mui-media';
					li.innerHTML = 
								'<a href="javascript:;" class="mui-navigate-right">'+
									'<div class="mui-media-body">'+arry.parameterType[i].name+'('+arry.parameterType[i].spec+')'+'</div>'+
								'</a>';	
			      }
			      mui('#pullrefresh').pullRefresh().endPulldownToRefresh();
			
			    }, 1500);
		  	}
	
	
			/**
			   * 上拉加载具体业务实现
			*/
		  	function pullupRefresh() {
		
		        jiaohu();
		        setTimeout(function() { 
		          mui('#pullrefresh').pullRefresh().endPullupToRefresh((++count >= totalNumber+1)); //参数为true代表没有更多数据了。
		          var table = document.body.querySelector('.mui-table-view');
		          var cells = document.body.querySelectorAll('.mui-table-view-cell');		          
		          for(var i = 0, len = i + 10; i < len; i++) {
		            var li = document.createElement('li');
		            li.className = 'mui-table-view-cell mui-media';										
					li.innerHTML = 
								'<a href="javascript:;" class="mui-navigate-right">'+
									'<div class="mui-media-body">'+arry.parameterType[i].name+'('+arry.parameterType[i].spec+')'+'</div>'+
								'</a>';	
												
		            table.appendChild(li);
		          }
		
		        }, 1500);
		  	}
	
		  	if(mui.os.plus) {
		        mui.plusReady(function() {
		          	setTimeout(function() {
		            	mui('#pullrefresh').pullRefresh().pullupLoading();
		      		}, 1000);
		
		        });
		  	} else {
		        mui.ready(function() {
		          mui('#pullrefresh').pullRefresh().pullupLoading();
		        });
		  	}
		
			/**
			   * 判断是否有历史记录
			*/
			if($('.word-break').length > 0) $('#hisAll').show();
		    else $('#hisAll').hide();
		</script>
	</body>
</html>